import { createRequest } from '@sa/axios';
import axios from 'axios';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { useAuthStore } from '@/store/modules/auth';
import { getToken } from '../../service/request/shared';
import { getServiceBaseURL } from '@/utils/service';
import { saveAs } from 'file-saver';

const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { otherBaseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);

// 错误代码映射
const errorCode = {
  '401': '认证失败，无法访问系统资源',
  '403': '当前操作没有权限',
  '404': '访问资源不存在',
  'default': '系统未知错误'
};

// 创建专用于下载的axios实例
const downloadAxios = axios.create({
  baseURL: otherBaseURL.api,
  timeout: 60000, // 下载文件时间可能较长，设置60秒超时
});

// 添加请求拦截器
downloadAxios.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers.token = token;
    }

    // 设置语言
    const language = localStorage.getItem('language');
    if (language) {
      config.headers['Accept-Language'] = language;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
downloadAxios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    const authStore = useAuthStore();

    // 处理401错误
    if (error.response?.status === 401) {
      ElMessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        showCancelButton: false,
        showClose: false,
        type: 'warning',
        closeOnPressEscape: false,
        closeOnClickModal: false
      }).then(() => {
        authStore.resetStore();
      });
      return Promise.reject(error);
    }

    ElMessage.error(error.message || '下载文件出现错误！');
    return Promise.reject(error);
  }
);

// 保留原有的createRequest实例用于向后兼容
const downloadRequest = createRequest(
  {
    baseURL: otherBaseURL.api,
    timeout: 60000,
  },
  {
    async onRequest(config) {
      const token = getToken();
      Object.assign(config.headers, { token });

      const language = localStorage.getItem('language');
      if (language) {
        config.headers['Accept-Language'] = language;
      }

      return config;
    },
    isBackendSuccess(response) {
      if (response.config?.responseType === 'blob' || response.config?.responseType === 'arraybuffer') {
        return true;
      }
      return response.data?.success === 1;
    },
    async onBackendFail(response) {
      return null;
    },
    async onError(error) {
      const authStore = useAuthStore();

      if (error.response?.status === 401) {
        ElMessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          showCancelButton: false,
          showClose: false,
          type: 'warning',
          closeOnPressEscape: false,
          closeOnClickModal: false
        }).then(() => {
          authStore.resetStore();
        });
        return;
      }

      ElMessage.error(error.message || '下载文件出现错误！');
    },
    transformBackendResponse(response) {
      return response.data;
    }
  }
);

let downloadLoadingInstance = null;

/**
 * 验证blob数据是否为有效文件
 * @param {Blob} data blob数据
 * @returns {Promise<boolean>} 是否为有效文件
 */
async function blobValidate(data) {
  try {
    // 如果是JSON格式的错误响应，说明不是有效文件
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch {
    // 解析失败说明是二进制文件数据
    return true;
  }
}

/**
 * 从响应头获取文件名
 * @param {Headers} headers 响应头
 * @returns {string} 文件名
 */
function getFileNameFromHeaders(headers) {
  console.log(headers);
  try {
    return window.decodeURIComponent(headers['content-disposition'].split('=')[1], 'UTF-8').replace(/utf-8''/, '')
  } catch (e) {
    console.error('解析文件名失败:', e);
  }
  return +new Date() + '.xlsx'
}

/**
 * 下载文件的通用方法（使用浏览器原生下载）
 * @param {Blob} blob 文件blob数据
 * @param {string} filename 文件名
 */
function downloadFile(blob, filename) {
  // 如果支持file-saver，使用file-saver
  saveAs(blob, filename)
}

/**
 * POST方式下载文件
 * @param {string} url 下载地址
 * @param {object} params 请求参数
 * @param {string} filename 文件名（可选）
 * @returns {Promise} 下载请求的Promise
 */
export function download(url, params = {}, filename = '') {
  downloadLoadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  return downloadAxios({
    method: 'POST',
    url,
    data: params,
    headers: {
      'Content-Type': 'application/json'
    },
    responseType: 'blob'
  }).then(async (response) => {
    console.log('完整response对象:', response);
    console.log('response.headers:', response.headers);
    const data = response.data;
    const isValidFile = await blobValidate(data);

    if (isValidFile) {
      const blob = new Blob([data]);
      if (!filename) {
        filename = getFileNameFromHeaders(response.headers);
      }
      downloadFile(blob, filename);
      ElMessage.success('文件下载成功');
    } else {
      // 处理后端返回的错误信息
      const resText = await data.text();
      try {
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.message || errorCode['default'];
        ElMessage.error(errMsg);
      } catch {
        ElMessage.error('下载文件失败，请重试');
      }
    }
  }).catch((error) => {
    console.error('下载失败:', error);
    ElMessage.error('下载文件出现错误！');
  }).finally(() => {
    if (downloadLoadingInstance) {
      downloadLoadingInstance.close();
      downloadLoadingInstance = null;
    }
  });
}

/**
 * GET方式下载文件
 * @param {string} url 下载地址
 * @param {string} filename 文件名（可选）
 * @param {object} params 查询参数（可选）
 * @returns {Promise} 下载请求的Promise
 */
export function getDownload(url, filename = '', params = {}) {
  downloadLoadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  return downloadAxios({
    method: 'GET',
    url,
    params,
    headers: {
      'Content-Type': 'application/json'
    },
    responseType: 'blob'
  }).then(async (response) => {
    const data = response.data;
    const isValidFile = await blobValidate(data);

    if (isValidFile) {
      const blob = new Blob([data]);
      if (!filename) {
        filename = getFileNameFromHeaders(response.headers);
      }
      downloadFile(blob, filename);
      ElMessage.success('文件下载成功');
    } else {
      // 处理后端返回的错误信息
      const resText = await data.text();
      try {
        const rspObj = JSON.parse(resText);
        const errMsg = errorCode[rspObj.code] || rspObj.message || errorCode['default'];
        ElMessage.error(errMsg);
      } catch {
        ElMessage.error('下载文件失败，请重试');
      }
    }
  }).catch((error) => {
    console.error('下载失败:', error);
    ElMessage.error('下载文件出现错误，请联系管理员！');
  }).finally(() => {
    if (downloadLoadingInstance) {
      downloadLoadingInstance.close();
      downloadLoadingInstance = null;
    }
  });
}

/**
 * 直接通过URL下载文件（适用于静态文件或已授权的下载链接）
 * @param {string} url 下载链接
 * @param {string} filename 文件名
 */
export function downloadByUrl(url, filename) {
  const link = document.createElement('a');
  link.href = url;
  link.download = filename || 'download';
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

/**
 * 批量下载文件
 * @param {Array} downloads 下载任务数组 [{url, params, filename}]
 * @returns {Promise} 批量下载的Promise
 */
export function batchDownload(downloads) {
  if (!downloads || downloads.length === 0) {
    ElMessage.warning('没有需要下载的文件');
    return Promise.resolve();
  }

  downloadLoadingInstance = ElLoading.service({
    text: `正在下载文件 (0/${downloads.length})`,
    background: 'rgba(0, 0, 0, 0.7)'
  });

  const downloadTasks = downloads.map((item, index) => {
    return download(item.url, item.params, item.filename).then(() => {
      // 更新进度
      if (downloadLoadingInstance) {
        downloadLoadingInstance.setText(`正在下载文件 (${index + 1}/${downloads.length})`);
      }
    });
  });

  return Promise.allSettled(downloadTasks).then((results) => {
    const successCount = results.filter(result => result.status === 'fulfilled').length;
    const failCount = downloads.length - successCount;

    if (failCount === 0) {
      ElMessage.success(`所有文件下载完成 (${successCount}个)`);
    } else {
      ElMessage.warning(`下载完成：成功 ${successCount}个，失败 ${failCount}个`);
    }
  }).finally(() => {
    if (downloadLoadingInstance) {
      downloadLoadingInstance.close();
      downloadLoadingInstance = null;
    }
  });
}

// 导出下载请求实例，供其他地方使用
export { downloadRequest };

export default {
  download,
  getDownload,
  downloadByUrl,
  batchDownload,
  downloadRequest
};
